package com.yxhl.km.module.person.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.text.style.UpdateLayout;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

import com.yxhl.km.R;
import com.yxhl.km.base.BaseActivity;
import com.yxhl.km.module.entity.EventBean;
import com.yxhl.km.module.person.entity.UploadBean;
import com.yxhl.km.module.person.entity.UserInfo;
import com.yxhl.km.module.person.mvp.PersonPrensenter;
import com.yxhl.km.module.utils.AppInfoUtil;
import com.yxhl.km.module.utils.CarameUtil;
import com.yxhl.km.module.utils.Constants;
import com.yxhl.km.module.utils.LogUtil;
import com.yxhl.km.module.utils.PicassoUtil;
import com.yxhl.km.module.utils.ToastUtil;
import com.yxhl.km.module.utils.album.CommonUtil;
import com.yxhl.km.module.utils.album.PhotoUtil;
import com.yxhl.km.module.utils.mission.OnPerMissionResult;
import com.yxhl.km.module.utils.mission.PerMissionUtils;
import com.yxhl.km.module.view.DiagUtil;
import com.yxhl.km.module.widget.CircleImageView;
import com.yxhl.km.mvp.BaseView;
import com.zhy.autolayout.AutoRelativeLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * Created by 张亚楠 on 2018/7/4.
 */

public class EditPersonActivity extends BaseActivity {
    @BindView(R.id.iv_head)
    CircleImageView ivHead;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.tv_ascription)
    TextView tvAscription;
    @BindView(R.id.tv_position)
    TextView tvPosition;
    @BindView(R.id.tv_rank)
    TextView tvRank;
    @BindView(R.id.tv_version)
    TextView tvVersion;
    @BindView(R.id.rl_iv_head)
    AutoRelativeLayout rlIvHead;
    private String[] permission = {Manifest.permission.WRITE_EXTERNAL_STORAGE
            , Manifest.permission.CAMERA};
    private String[] namePermission = {"修改存储权限", "打开相机权限"};

    @Override
    protected void initListener() {
        rlIvHead.setOnClickListener(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_editperson;
    }

    @Override
    protected void initialized(android.os.Bundle savedInstanceState) {
        initTitle("", "个人信息", "");
        titlebar_left_iv.setVisibility(View.VISIBLE);
        tvVersion.setText("V " + AppInfoUtil.getAppVersionName(this));
        cache = CommonUtil.getCacheDir(this);
        file = new File(cache, "head.jpg");
        requstUser();
    }

    private void requstUser() {
        DiagUtil.getInstance().createWaitDialog(EditPersonActivity.this);
        PersonPrensenter personPrensenter = new PersonPrensenter(new BaseView<UserInfo>() {
            @Override
            public void onResult(UserInfo userInfo) {
                DiagUtil.getInstance().closeWaitDialog();
                if (!TextUtils.isEmpty(userInfo.getData().getName())) {
                    tvName.setText(userInfo.getData().getName());
                }
                if (!TextUtils.isEmpty(userInfo.getData().getPhone())) {
                    tvPhone.setText(userInfo.getData().getPhone());
                }
                if (1 == userInfo.getData().getUserType() && !TextUtils.isEmpty(userInfo.getData().getFarmName())) {
                    tvAscription.setText(userInfo.getData().getFarmName());
                } else if (2 == userInfo.getData().getUserType()) {
                    tvAscription.setText(userInfo.getData().getCompanyFlag() == 1 ? "linkage" : "farmfrites");
                }
                if (null != userInfo.getData().getRoleList() && userInfo.getData().getRoleList().size() >= 1) {
                    tvPosition.setText(userInfo.getData().getRoleList().get(0).getName());
                }
                tvRank.setText(userInfo.getData().getLevel() + "");
                if (!TextUtils.isEmpty(userInfo.getData().getHeadimg())) {
                    PicassoUtil.LoadPicasso(EditPersonActivity.this, userInfo.getData().getHeadimg(), ivHead);
                }

            }
        });

        if (!TextUtils.isEmpty(getUserInfo().getData().getUser().getId())) {
            personPrensenter.getUserData(getUserInfo().getData().getUser().getId());
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        requstUser();
    }

    private static final String IMAGE_UNSPECIFIED = "image/*";
    private File file;
    private File cache;
    public static Bitmap photo;

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            /**
             * 头像
             */
            case R.id.rl_iv_head:
                PerMissionUtils.getInstance().getMission(mContext, permission, namePermission, new OnPerMissionResult() {
                    @Override
                    public void onPermissionGranted() {
                        Intent intent = new Intent(Intent.ACTION_PICK, null);
                        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_UNSPECIFIED);
                        showPhotoDialog(EditPersonActivity.this, intent, Constants.PHOTOZOOM, file);
                    }

                    @Override
                    public void onNoPermission() {

                    }
                });

                break;
        }

    }

    /**
     * 弹出 相册 照像机 选择框
     */
    private void showPhotoDialog(final BaseActivity act, final Intent intent, final int requestCode, final File file) {
        View view = mContext.getLayoutInflater().inflate(R.layout.photo_choose_dialog, null);
        final Dialog dialog = new Dialog(mContext, R.style.transparentFrameWindowStyle);
        Button photo_album = (Button) view.findViewById(R.id.photo_album);
        Button take_photo = (Button) view.findViewById(R.id.take_phone);
        Button cancle = (Button) view.findViewById(R.id.dialog_cancle);
        photo_album.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                startActivityForResult(intent, requestCode);
                dialog.dismiss();
            }
        });
        take_photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startCamera(act, file);
                dialog.dismiss();
            }
        });
        cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();

            }
        });
        dialog.setContentView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        Window window = dialog.getWindow();
        // 设置显示动画
        window.setWindowAnimations(R.style.main_menu_animstyle);
        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        wl.y = mContext.getWindowManager().getDefaultDisplay().getHeight();
        // 满屏显示
        wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        // 设置显示位置
        dialog.onWindowAttributesChanged(wl);
        // 设置点击外围解散
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
    }

    private void startCamera(BaseActivity act, File file) {
        if (!CarameUtil.isSupportCameraFeature(act)) {
            ToastUtil.makeToast("摄像头不能用");
            return;
        } else {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
            Uri uri = FileProvider.getUriForFile(mContext, "com.yxhl.km.fileprovider", file);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            act.startActivityForResult(intent, Constants.CARAME);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        setHeadimg(requestCode, resultCode, data);
    }

    private void setHeadimg(int requestCode, int resultCode, Intent data) {
        if (resultCode == Constants.NONE) {
            return;
        }
        // 拍照
        if (requestCode == Constants.CARAME) {
            try {
                // 生成图片
                Bitmap photo = PhotoUtil.cacheImage(file);
                if (photo == null) {
                    return;
                }
                //     imageBitmap.add(photo);
                // 保存图片
                File cachefile = new File(cache, "head.jpg");
                try {
                    PhotoUtil.saveBitmap(cachefile, photo);
                } catch (Exception e) {
                    return;
                }
                Uri uri = FileProvider.getUriForFile(mContext, "com.yxhl.km.fileprovider", cachefile);
                startPhotoZoom(uri);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        if (data == null) {
            return;
        }
        // 读取相册缩放图片
        if (requestCode == Constants.PHOTOZOOM) {
            startPhotoZoom(data.getData());
        }
        if (requestCode == Constants.PHOTORESOULT) {
            Bundle extras = data.getExtras();
            if (extras != null) {
                photo = extras.getParcelable("data");
                // 保存图片
                File cachefile = new File(cache, String.valueOf(String.valueOf(System.currentTimeMillis()).hashCode()) + ".jpg");
                try {
                    PhotoUtil.saveBitmap(cachefile, photo);
                } catch (Exception e) {
                    return;
                }
                upLoadImage(cachefile);
            }
        }
    }

    private void upLoadImage(File cachefile) {
        DiagUtil.getInstance().createWaitDialog(EditPersonActivity.this);
        PersonPrensenter personPrensenter = new PersonPrensenter(new BaseView<UploadBean>() {
            @Override
            public void onResult(UploadBean uploadBean) {
                DiagUtil.getInstance().closeWaitDialog();
                updateImaHead(uploadBean);
            }
        });

        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM);//表单类型
        RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), cachefile);
        builder.addFormDataPart("file", cachefile.getName(), imageBody);//imgfile 后台接收图片流的参数名
        List<MultipartBody.Part> parts = builder.build().parts();
        personPrensenter.getUserHeadImagData(parts);
    }

    private void updateImaHead(UploadBean uploadBean) {
        if (!TextUtils.isEmpty(uploadBean.getData().getUrl())) {
            EventBus.getDefault().post(new EventBean<String>(Constants.EVENTVUS_EDIT_ICON, uploadBean.getData().getUrl()));
            PicassoUtil.LoadPicasso(mContext, uploadBean.getData().getUrl(), ivHead);
        }
    }
    private void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
        //需要加上这两句话  ： uri 权限
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 200);
        intent.putExtra("outputY", 200);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, Constants.PHOTORESOULT);
    }

    @Override
    protected void onCreate(android.os.Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
